<?php
/**
 * Created by PhpStorm.
 * User: 胥九庆
 * Date: 2023/01/04
 * Time: 17:26
 */
declare (strict_types=1);

namespace app\common\model;

class CourseHit extends Base
{
    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile');
    }

    public function course()
    {
        return $this->hasOne(Course::class, 'id', 'course_id')->field('id,title');
    }

    public static function hit($param, $uid)
    {
        parent::startTrans();
        try {
            $info = parent::where(['course_id' => $param['course_id'], 'uid' => $uid])->find();
            if ($info) {
                $info->delete();
                Course::where('id', $param['course_id'])->dec('total_hit')->update();
                $msg = '取消成功';
            } else {
                $param['uid'] = $uid;
                parent::create($param);
                Course::where('id', $param['course_id'])->inc('total_hit')->update();
                $msg = '点赞成功';
            }
            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => $msg];
    }
}